/************************************************************
** @Description: FYKJ_Admin
** @Author: dabin
** @Date:   2021-03-02 21:21
** @Last Modified by:   dabin
** @Last Modified time: 2021-03-02 21:21
*************************************************************/
package user

//用户模块
import (
	"FYKJ_Admin/models/auth"
	_ "FYKJ_Admin/models/auth"
	"FYKJ_Admin/utils"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"math"
	"strings"
)

type UserController struct {
	beego.Controller
}

func (u *UserController) List() {
	//o := orm.NewOrm()
	//qs :=o.QueryTable("sys_user")
	//users := []user.User{}
	//// 每页显示的条数
	//pagePerNum :=2
	//// 当前页
	//currentPage,err := u.GetInt("page")
	//if err != nil{ //说明没有获取到当前页
	//	currentPage =1
	//}
	//// 总记录数
	//count,_ :=qs.Filter("is_delete",0).Count()
	//// 总页数
	//countPage := int(math.Ceil(float64(count) / float64(pagePerNum)))
	//// 偏移量
	//offsetNum := pagePerNum * (currentPage - 1)
	//qs.Filter("is_delete",0).Limit(pagePerNum).Offset(offsetNum).All(&users)
	///*   分页逻辑
	//     当前第几页    offset    limit
	//     1            0         2        2* (1-1)
	//     2            2         2        2*（2-1）
	//     3            4         2        2*（3-1）
	//     分页数*（当前页-1）   limitNum * (currentPage -1)
	// */
	//// 上一页
	//prePage := 1
	//if currentPage == 1 {
	//	prePage = currentPage
	//}else if currentPage > 1 {
	//	prePage = currentPage-1
	//}
	//// 下一页
	//nextPage := 1
	//if currentPage < countPage {
	//	nextPage = currentPage + 1
	//}else if currentPage >= countPage {
	//	nextPage = countPage
	//}
	o := orm.NewOrm()
	qs := o.QueryTable("sys_user")
	users := []auth.User{}
	// 每页显示的条数
	pagePerNum := 5
	// 当前页
	currentPage, err := u.GetInt("page")

	//收索查询功能，入参
	kw := u.GetString("kw")
	// 偏移量
	offsetNum := pagePerNum * (currentPage - 1)
	//打印查询信息
	ret :=fmt.Sprintf("用户查询信息，当前页：%d;查询条件:%s",currentPage,kw)
	logs.Info(ret)

	//如果没有变量需要使用自动推导 := ,有变量直接 = ，例如count := 0 默认int类型
	var count int64 = 0
	if kw != "" { //有查询条件的
		// 总记录数 ,,__contains包含列
		count, _ = qs.Filter("is_delete", 0).Filter("user_name__contains",kw).Count()
		qs.Filter("is_delete", 0).Filter("user_name__contains",kw).Limit(pagePerNum).Offset(offsetNum).All(&users)
	}else {
		// 总记录数
		count, _ = qs.Filter("is_delete", 0).Count()
		qs.Filter("is_delete", 0).Limit(pagePerNum).Offset(offsetNum).All(&users)
	}
	if err != nil { //说明没有获取到当前页
		currentPage = 1
	}

	// 总页数
	countPage := int(math.Ceil(float64(count) / float64(pagePerNum)))


	/*   分页逻辑
	     当前第几页    offset    limit
	     1            0         2        2* (1-1)
	     2            2         2        2*（2-1）
	     3            4         2        2*（3-1）
	     分页数*（当前页-1）   limitNum * (currentPage -1)
	*/
	// 上一页
	prePage := 1
	if currentPage == 1 {
		prePage = currentPage
	} else if currentPage > 1 {
		prePage = currentPage - 1
	}
	// 下一页
	nextPage := 1
	if currentPage < countPage {
		nextPage = currentPage + 1
	} else if currentPage >= countPage {
		nextPage = countPage
	}

	page_map := utils.Paginator(currentPage, pagePerNum, count)
	u.Data["users"] = users
	u.Data["prePage"] = prePage
	u.Data["nextPage"] = nextPage
	u.Data["currentPage"] = currentPage
	u.Data["countPage"] = countPage
	u.Data["count"] = count
	u.Data["page_map"] = page_map
	u.Data["kw"] = kw
	u.TplName = "user/user_list.html"
}
//弹出添加页面
func (u *UserController) Add() {
	u.TplName = "user/user_add.html"
}
//做添加操作传参
func (u *UserController) DoAdd() {
	job_id := u.GetString("job_id")
	username := u.GetString("username")
	nickname := u.GetString("nickname")
	pass_word := u.GetString("pass_word")
	age,_ := u.GetInt("age")
	gender,_ := u.GetInt("gender")
	phone,_ := u.GetInt64("phone")
	addr := u.GetString("addr")
	email := u.GetString("email")
	card_id := u.GetString("card_id")
	head_portrait := u.GetString("head_portrait")
	is_active,_ := u.GetInt("is_active")

	new_password := utils.GetMd5File(pass_word)
	o :=orm.NewOrm()
	user_date :=auth.User{UserName:username,NickName:nickname,PassWord:new_password,Age:age,Gender:gender,Phone:phone,Addr:addr,
		Email:email,CardId:card_id,HeadPortrait:head_portrait,IsActive:is_active,JobId:job_id}

	_,err := o.Insert(&user_date)
	message_map := map[string]interface{}{}
	if err != nil { //说明插入数据有问题
		ret_addinfo :=fmt.Sprintf("添加数据出错，添加信息：username%s|nickname%s|pass_word%s|age%d|gender%d|" +
			"phone%d|addr%s|email%s|card_id%s|head_portrait%s|is_active%d|job_id%s",username,nickname,pass_word,age,gender,
			phone,addr,email,card_id,head_portrait,is_active,job_id)
		ret :=fmt.Sprintf("添加数据出错，错误信息：%v",err)
		logs.Error(ret_addinfo)
		logs.Error(ret)
		message_map["code"] = 1001
		message_map["msg"] = "添加数据出错，请重新添加！"
		u.Data["json"] = message_map
	}else {
		ret_addinfo :=fmt.Sprintf("添加数据成功，添加信息：username%s|nickname%s|pass_word%s|age%d|gender%d|" +
			"phone%d|addr%s|email%s|card_id%s|head_portrait%s|is_active%d|job_id%s",username,nickname,pass_word,age,gender,
			phone,addr,email,card_id,head_portrait,is_active,job_id)
		logs.Info(ret_addinfo)
		message_map["code"] = 200
		message_map["msg"] = "添加成功！"
		u.Data["json"] = message_map
	}
	u.ServeJSON()
}
//停用启用
func (u *UserController) IsActive() {
	is_active,_ := u.GetInt("is_active_val")
	sys_id,_ := u.GetInt("sys_id")
	o := orm.NewOrm()
	qs := o.QueryTable("sys_user").Filter("sys_id",sys_id)
	message_map := map[string]interface{}{}
	if is_active == 1 {
		qs.Update(orm.Params{
			"is_active": 2,
		})
		ret := fmt.Sprintf("停用/启用功能，用户id:%d,停用成功",sys_id)
		logs.Info(ret)
		message_map["msg"] = "停用成功"
	}else if is_active == 2 {
		qs.Update(orm.Params{
			"is_active": 1,
		})
		ret := fmt.Sprintf("停用/启用功能，用户id:%d,启用成功",sys_id)
		logs.Info(ret)
		message_map["msg"] = "启用成功"
	}

	u.Data["json"] = message_map
	u.ServeJSON()
}
//删除用户
func (u *UserController) Delete() {
	sys_id,_ := u.GetInt64("sys_id")
	is_delete_val,_ := u.GetInt("is_delete_val")
	o :=orm.NewOrm()
	// 直接delete删除物理删除
	//o.QueryTable("sys_user").Filter("SysId",SysId).Delete()
	//逻辑删除，修改状态
	qs := o.QueryTable("sys_user").Filter("sys_id",sys_id)
	message_map := map[string]interface{}{}
	if is_delete_val ==0 {
		qs.Update(orm.Params{
			"is_delete": 1,
		})
		ret := fmt.Sprintf("删除功能，用户id:%d,删除成功",sys_id)
		logs.Info(ret)
		message_map["msg"] = "删除成功！"
	}
	u.Data["json"] = message_map
	u.ServeJSON()
	// 重定向页面（刷新页面）
	//u.Redirect(beego.URLFor("UserController.List"),302)
}
//弹出重置密码界面
func (u *UserController) RetSetPwd() {
	sys_id,_ := u.GetInt64("sys_id")
	o := orm.NewOrm()
	//定义一个容器
	users := auth.User{}
	o.QueryTable("sys_user").Filter("sys_id",sys_id).One(&users)
	u.Data["user"] =users
	u.TplName = "user/user_password.html"
}
//去根据传参进行重置密码
func (u *UserController) DoRetSetPwd() {
	sys_id,_ := u.GetInt64("sys_id")

	old_pass_word := u.GetString("old_pass_word")
	new_pass_word := u.GetString("new_pass_word")
	new_pwd := utils.GetMd5File(new_pass_word)
	old_pwd := utils.GetMd5File(old_pass_word)
	o := orm.NewOrm()
	qs := o.QueryTable("sys_user").Filter("sys_id",sys_id)
	userinfo := auth.User{}
	qs.One(&userinfo)
	message_map := map[string]interface{}{}
	if old_pwd != userinfo.PassWord {
		ret := fmt.Sprintf("重置密码功能，错误信息，用户id:%d|旧密码:%s|新密码:%s",sys_id,old_pwd,new_pwd)
		logs.Error(ret)
		message_map["code"] = 1001
		message_map["msg"] = "源密码输入错误！"
	}else if userinfo.PassWord != new_pwd {
		qs.Update(orm.Params{
			"pass_word": new_pwd,
		})
		ret := fmt.Sprintf("重置密码功能，用户信息,用户id:%d|旧密码:%s|新密码:%s",sys_id,old_pwd,new_pwd)
		logs.Info(ret)
		message_map["code"] = 200
		message_map["msg"] = "重置密码成功"
	}
	u.Data["json"] = message_map
	u.ServeJSON()
}

//编辑用户信息
func (u *UserController) ToUpdate() {
	sys_id,_ := u.GetInt64("sys_id")
	o := orm.NewOrm()
	//定义一个容器
	user_data := auth.User{}
	o.QueryTable("sys_user").Filter("sys_id",sys_id).One(&user_data)
	u.Data["user"] =user_data
	u.TplName = "user/user_edit.html"
}

func (u *UserController) DoUpdate() {
	sys_id,_ := u.GetInt64("sys_id")
	job_id := u.GetString("job_id")
	username := u.GetString("username")
	nickname := u.GetString("nickname")
	pass_word := u.GetString("pass_word")
	age,_ := u.GetInt("age")
	gender,_ := u.GetInt("gender")
	phone,_ := u.GetInt64("phone")
	addr := u.GetString("addr")
	email := u.GetString("email")
	card_id := u.GetString("card_id")
	head_portrait := u.GetString("head_portrait")
	is_active,_ := u.GetInt("is_active")
	new_pwd := utils.GetMd5File(pass_word)

	o := orm.NewOrm()
	qs := o.QueryTable("sys_user").Filter("sys_id",sys_id)
	message_map := map[string]interface{}{}
	if pass_word =="" {
		_,err := qs.Update(orm.Params{
			"job_id" : job_id,
			"username" : username,
			"nickname" : nickname,
			"age" : age,
			"gender" : gender,
			"phone" : phone,
			"addr" : addr,
			"email" : email,
			"card_id" : card_id,
			"head_portrait" : head_portrait,
			"is_active" : is_active,
		})
		if err != nil {
			ret := fmt.Sprintf("编辑用户功能，错误信息，username:%s|nickname:%s|age:%d|gender%d|phone%d|addr%s" +
				"|email%s|card_id%s|head_portrait%s|is_active%d",username,nickname,age,gender,phone,addr,email,card_id,
			head_portrait,is_active)
			logs.Error(ret)
			message_map["code"] = 10001
			message_map["msg"] = "更新失败"
		}else {
			ret := fmt.Sprintf("编辑用户功能，错误信息，username:%s|nickname:%s|age:%d|gender%d|phone%d|addr%s" +
				"|email%s|card_id%s|head_portrait%s|is_active%d",username,nickname,age,gender,phone,addr,email,card_id,
				head_portrait,is_active)
			logs.Info(ret)
			message_map["code"] = 200
			message_map["msg"] = "更新成功"
		}
	}else {
		_,err := qs.Update(orm.Params{
			"username" : username,
			"nickname" : nickname,
			"pass_word" : new_pwd,
			"age" : age,
			"gender" : gender,
			"phone" : phone,
			"addr" : addr,
			"email" : email,
			"card_id" : card_id,
			"head_portrait" : head_portrait,
			"is_active" : is_active,
		})
		if err != nil {
			ret := fmt.Sprintf("编辑用户功能，错误信息，username:%s|nickname:%s|pass_word%s|age:%d|gender%d|phone%d|addr%s" +
				"|email%s|card_id%s|head_portrait%s|is_active%d",username,nickname,pass_word,age,gender,phone,addr,email,card_id,
				head_portrait,is_active)
			logs.Error(ret)
			message_map["code"] = 10001
			message_map["msg"] = "更新失败"
		}else {
			ret := fmt.Sprintf("编辑用户功能，错误信息，username:%s|nickname:%s|pass_word%s|age:%d|gender%d|phone%d|addr%s" +
				"|email%s|card_id%s|head_portrait%s|is_active%d",username,nickname,pass_word,age,gender,phone,addr,email,card_id,
				head_portrait,is_active)
			logs.Info(ret)
			message_map["code"] = 200
			message_map["msg"] = "更新成功"
		}
	}
	u.Data["json"] = message_map
	u.ServeJSON()

}
//批量删除
func (u *UserController) MuliDelete() {
	ids := u.GetString("ids")
	//得到的结果"3,7,8,9",需要截取掉两边引号为 3,7,8,9
	new_ids :=ids[1:len(ids)-1]
	//，切割符号为逗号
	id_arr := strings.Split(new_ids,",")
	o := orm.NewOrm()
	qs := o.QueryTable("sys_user")
	for _, v := range id_arr{
		//字符串转int64
		id_int := utils.StrToInt(v)
		qs.Filter("sys_id",id_int).Update(orm.Params{
			"is_delete":1,
		})
	}
	ret :=fmt.Sprintf("批量删除功能，批量删除成功：用户ids:%s;",ids)
	logs.Info(ret)
	u.Data["json"] = map[string]interface{}{"code":200,"msg":"批量删除成功！"}
	u.ServeJSON()
}